const envConfig = require('./proxy.config');

// 开发环境cookie缓存和交换
const cookies = {
  current: null,
};

const devDomain = envConfig.getDomain();

const IP = process.env.IP;

let localProxy;

if (IP) {
  localProxy = {
    target: `${devDomain.target}`,
    headers: {
      'origin': `${devDomain.origin}`,
      'referer': `${devDomain.origin}`,
      'sec-fetch-site': 'same-site',
      'sec-fetch-mode': 'cors',
      'sec-fetch-dest': 'empty',
    },
    changeOrigin: true, // 是否跨域
    secure: true, // 是否https接口
    onError(err, req, res) {
      console.log('err', err);
    },
    onProxyReq(proxyReq, req, res) {
      if (proxyReq._headers.myorigin) {
        proxyReq.setHeader('origin', proxyReq._headers.myorigin);
        proxyReq.setHeader('referer', proxyReq._headers.myorigin);
      }
      // proxyReq.setHeader('cookie', proxyReq._headers.cookie);
      // proxyReq.setHeader('cookie', proxyReq._headers.cookie || cookies.current);
      // console.log('\nproxyReq origin2', proxyReq.path, proxyReq._headers.origin, proxyReq._headers.referer, proxyReq._headers);
      // console.log('path', proxyReq.path, proxyReq._headers);
    },
    onProxyRes(proxyRes, req, res) {
      // console.log('\nstatusCode', proxyRes.statusCode);
      // console.log('\nstatusMessage', proxyRes.statusMessage);
      // console.log('\nheaders', proxyRes.headers);
      // console.log('\ncookies', proxyRes.headers['set-cookie']);

      proxyRes.headers['access-control-allow-origin'] = req.headers['origin'];

      if (proxyRes.headers['set-cookie'] !== undefined) {
        // console.log('** SET-COOKIE: ', proxyRes.headers['set-cookie']);
        cookies.current = proxyRes.headers['set-cookie']
          .map((d) => d.replace(/Path=.+$/, ''))
          .join(';');
        // console.log('cookies.current', cookies.current);
        proxyRes.headers['set-cookie'] = proxyRes.headers['set-cookie'].map((d) =>
          d.replace(/Domain=\w+\.\w+;/, ``)
        );
      }
    },
  };
}

module.exports = localProxy;
